﻿using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Xml;

namespace WebApplication1
{
    public class Util
    {
        //public static string appid = "wx4af7db8449b786b1"; //微信公众号appid
        //public static string secret = "f052c07e81ebc9a13671f67b376c8bbf";  //微信公众号appsecret

        public static string appid = "wx280555fd8890b0f0"; //测试公众号appid
        public static string secret = "f99e033b62363a0cc64930180739a64c";  //测试公众号appsecret

        public static string msg = "";

        #region 调用微信api

        //        获取access_token请求说明

        //是以http请求的GET方式通过访问：
        //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
        //参数说明
        //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&APPID=wx280555fd8890b0f0&secret=f99e033b62363a0cc64930180739a64c //测试公众号
        //参数  是否必须 说明
        //grant_type 是   获取access_token填写client_credential
        //appid   是 第三方用户唯一凭证
        //secret 是   第三方用户唯一凭证密钥，即appsecret
        //访问完成之后，如果成功则微信会返回JSON包，JSON包格式为：

        //{"access_token":"ACCESS_TOKEN","expires_in":7200}

        //如果JSON包返回的结果是{"errcode":40013,"errmsg":"invalid appid"}则说明AppID无效。
        //参数 说明
        //access_token 获取到的凭证
        //expires_in 凭证有效时间，单位：秒

        /// <summary>
        /// 根据当前日期 判断Access_Token 是否超期  如果超期返回新的Access_Token   否则返回之前的Access_Token
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static string MyAccess_Token()
        {
            string Token = string.Empty;
            DateTime YouXRQ;
            // 读取XML文件中的数据，并显示出来 ，注意文件路径
            string filepath = HttpContext.Current.Server.MapPath(".") + "\\AccessToken.xml";

            StreamReader str = new StreamReader(filepath, Encoding.UTF8);
            XmlDocument xml = new XmlDocument();
            xml.Load(str);
            str.Close();
            str.Dispose();
            Token = xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText;
            YouXRQ = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText);

            //TimeSpan st1 = new TimeSpan(YouXRQ.Ticks); //最后刷新的时间
            //TimeSpan st2 = new TimeSpan(DateTime.Now.Ticks); //当前时间
            //TimeSpan st = st2 - st1; //两者相差时间
            if (DateTime.Now > YouXRQ)
            {
                DateTime _youxrq = DateTime.Now;
                Access_token mode = Get_Accesstoken();
                if (string.IsNullOrEmpty(mode.access_token) || string.IsNullOrEmpty(mode.expires_in))
                    return Token;

                xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText = mode.access_token;
                _youxrq = _youxrq.AddSeconds(int.Parse(mode.expires_in));
                xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText = _youxrq.ToString();
                xml.Save(filepath);
                Token = mode.access_token;
            }
            return Token;
        }



        /// <summary>
        /// 获取Access_token
        /// </summary>
        /// <returns></returns>
        public static Access_token Get_Accesstoken()
        {

            string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            Access_token token = new Access_token();

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl);  //用GET形式请求指定的地址 
            req.Method = "GET";

            using (WebResponse wr = req.GetResponse())
            {
                StreamReader reader = new StreamReader(wr.GetResponseStream(), Encoding.UTF8);
                string content = reader.ReadToEnd();
                msg = content;
                reader.Close();
                reader.Dispose();

                token = JsonHelper.ParseFromJson<Access_token>(content);

            }
            return token;
        }

        /// 获取jsapi_ticket,如果存在且没过期，则直接取jsapi_ticket
        /// </summary>
        /// <returns></returns>
        public static string GetJSTicket()
        {
            // 读取XML文件中的数据
            string filepath = System.Web.HttpContext.Current.Server.MapPath("/AccessToken.xml");
            FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            StreamReader str = new StreamReader(fs, System.Text.Encoding.UTF8);
            XmlDocument xml = new XmlDocument();
            xml.Load(str);
            str.Close();
            str.Dispose();
            fs.Close();
            fs.Dispose();
            string ticket = xml.SelectSingleNode("xml").SelectSingleNode("JSTicket").InnerText;
            DateTime AccessTokenExpires = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("JSAccessExpires").InnerText);
            //如果jsapi_ticket过期，则重新获取token
            if (DateTime.Now >= AccessTokenExpires)
            {
                string Token = MyAccess_Token();
                JSTicket mode = getJSTicketTicket(Token);
                if (mode.ticket != null && mode.expires_in != null)
                {
                    //将jsapi_ticket存到xml文件中，全局缓存
                    xml.SelectSingleNode("xml").SelectSingleNode("JSTicket").InnerText = mode.ticket;
                    DateTime _AccessTokenExpires = DateTime.Now.AddSeconds(int.Parse(mode.expires_in));
                    xml.SelectSingleNode("xml").SelectSingleNode("JSAccessExpires").InnerText = _AccessTokenExpires.ToString();
                    xml.Save(filepath);
                    ticket = mode.ticket;
                }
                else
                {
                    ticket = "";
                }
            }
            return ticket;
        }

        /// 获取jsapi_ticket
        /// </summary>
        /// <param name="access"></param>
        /// <returns></returns>
        private static JSTicket getJSTicketTicket(string access)
        {
            string strUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access + "&type=jsapi";
            JSTicket mode = new JSTicket();
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl);
            req.Method = "GET";
            using (WebResponse wr = req.GetResponse())
            {
                StreamReader reader = new StreamReader(wr.GetResponseStream(), Encoding.UTF8);
                string content = reader.ReadToEnd();
                msg = content;
                reader.Close();
                reader.Dispose();
                //获取解析回来的值
                mode = JsonHelper.ParseFromJson<JSTicket>(content);
            }
            return mode;

        }

        public static string GenSignature(string JSTicketTicket, string nonceStr, string timestamp, string url)
        {
            // 这里参数的顺序要按照 key 值 ASCII 码升序排序  
            string str_sha1_in = "jsapi_ticket=" + JSTicketTicket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url + "";
           

            return FormsAuthentication.HashPasswordForStoringInConfigFile(str_sha1_in, "SHA1").ToLower();
           
        }

        #endregion

        public static string GetJson(string url)
        {
            WebClient wc = new WebClient();
            wc.Credentials = CredentialCache.DefaultCredentials;
            wc.Encoding = Encoding.UTF8;
            string returnText = wc.DownloadString(url);

            if (returnText.Contains("errcode"))
            {
                //可能发生错误
            }
            //Response.Write(returnText);
            return returnText;
        }


        /// 将c# DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time">时间</param>  
        /// <returns>double</returns>  
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            int intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = Convert.ToInt32((time - startTime).TotalSeconds);
            return intResult;
        }


        /// 创建随机字符串
        /// </summary>
        /// <returns></returns>
        public static string CreateNonceStr()
        {
            int length = 16;
            string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string str = "";
            Random rad = new Random();
            for (int i = 0; i < length; i++)
            {
                str += chars.Substring(rad.Next(0, chars.Length - 1), 1);
            }
            return str;
        }

    }
    public static class JsonHelper
    {
        /// <summary>
        /// 生成Json格式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetJson<T>(T obj)
        {

            DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, obj);
                string szJson = Encoding.UTF8.GetString(stream.ToArray());
                return szJson;
            }
        }
        /// <summary>
        /// 获取Json的Model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="szJson"></param>
        /// <returns></returns>
        public static T ParseFromJson<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }




    }
}